package com.kalaqia.im.library.account;

import android.util.Log;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMChatManager;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;

import java.util.List;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.MainThreadDisposable;

/**
 * function:
 * project:kalaqia
 * describe:
 * created owner:kalaqia 421407393@qq.com
 * created date:2017/8/16 16:39
 */
//<editor-fold desc="version update log">
// updare owner:kalaqia  421407393@qq.com
// update datetime:2017/8/16 16:39 
// update remark:
//</editor-fold>
public class IMAccountObservable extends Observable<Boolean> {

    private EMClient client;
    private String userName;
    private String password;

    public IMAccountObservable(String userName, String password) {
        this(EMClient.getInstance(), userName, password);
    }

    public IMAccountObservable(EMClient client, String userName, String password) {
        this.client = client;
        this.userName = userName;
        this.password = password;
    }

    @Override
    protected void subscribeActual(Observer<? super Boolean> observer) {
        EMLoginDisposable disposable = new EMLoginDisposable(observer);
        observer.onSubscribe(disposable);
        client.login(userName, password, disposable);
    }

    private final class EMLoginDisposable extends MainThreadDisposable implements EMCallBack {

        public EMLoginDisposable(Observer<? super Boolean> observer) {
            this.observer = observer;
        }

        private final Observer<? super Boolean> observer;

        @Override
        public void onSuccess() {
            if (!isDisposed()) {
                observer.onNext(true);
            }
        }

        @Override
        public void onError(int i, String s) {
            if (!isDisposed()) {
                observer.onError(new Throwable(s));
            }
        }

        @Override
        public void onProgress(int i, String s) {

        }

        @Override
        protected void onDispose() {

        }
    }
}
